package calculator;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import Store.ClassDiagram;
import Store.EventCondReact;
import Store.Project;
import Store.StateMachine;
import Store.StateObserverInv;
import Store.StateTable;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class Serialization 
{

	public static Project deserialize(FileInputStream fis) throws IOException, ClassNotFoundException 
	{
		Project nuovoProgetto = null;
		String nome = null; 
		ClassDiagram inputCD = null;
		ClassDiagram outputCD = null;
		StateObserverInv stateObserverInv = null;
		StateMachine stateMachine = null;
		EventCondReact eventCondReact = null;
		StateTable stateTable = null;
		inputCD = new ClassDiagram();
		outputCD = new ClassDiagram();
		stateObserverInv = new StateObserverInv();
		stateMachine = new StateMachine();
		eventCondReact = new EventCondReact();
		stateTable = new StateTable();
		
		ObjectInputStream ois = null;
		XStream xs = new XStream(new DomDriver());
		xs.setMode(XStream.ID_REFERENCES);
		try {
			
			ois = xs.createObjectInputStream(fis);

			nome =(String)ois.readObject();
			inputCD = (ClassDiagram)ois.readObject();
			stateObserverInv= (StateObserverInv)ois.readObject();
			eventCondReact = (EventCondReact)ois.readObject();
			stateTable = (StateTable)ois.readObject();
			stateMachine = (StateMachine)ois.readObject();
			outputCD = (ClassDiagram)ois.readObject();

			ois.close();
			fis.close();
			}
		catch (FileNotFoundException e) {} 
		
		nuovoProgetto = new Project(nome, inputCD, outputCD, stateObserverInv, stateMachine, eventCondReact, stateTable);
		return nuovoProgetto;
	}

	public static FileOutputStream serialize(Project project) throws IOException
	{
		FileOutputStream fs = new FileOutputStream(""+project.getName()+".esm");
		
		XStream xs = new XStream();
        xs.setMode(XStream.ID_REFERENCES);
        ObjectOutputStream oos = xs.createObjectOutputStream(fs);
        
        oos.writeObject(project.getName());
        oos.writeObject(project.getInputCD());
        oos.writeObject(project.getStateObserverInv());
        oos.writeObject(project.getEventCondReact());
        oos.writeObject(project.getStateTable());
        oos.writeObject(project.getStateMachine());
        oos.writeObject(project.getOutputCD());
        
        oos.close();
		fs.close();
        
		System.out.println("Operazione Eseguita\n");
		
		return fs;
	}
}